﻿using Learn.Infraestrutura.Dto.Response;
using Learn.Infraestrutura.Tools;
using Learn.Service.Interface;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using MySqlX.XDevAPI.Common;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Learning.Api.Admin.Middles
{
    public class Exception_Middle
    {
        private readonly RequestDelegate _next;
        private readonly IConfiguration _configuration;


        public Exception_Middle(RequestDelegate next, IConfiguration configuration)
        {
            _next = next;
            _configuration = configuration;
          

        }

        public async Task InvokeAsync(HttpContext context,I_Log_Service log_Service)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                //管道中出现了异常 在此处统一处理

                string result = System.Text.Json.JsonSerializer.Serialize(new
                {
                    result = "-500",
                    message = "Custom Exception"
                });
                try
                {
                    //1.记录到本地
                    //获取请求参数
                    string paras = "";
                    #region 请求参数
                    if (context.Request.Method.ToUpper() == "GET")
                    {
                        var keys = context.Request.Query.Keys;
                        foreach (var item in keys)
                        {
                            paras += $"{item}={context.Request.Query[item]};";
                        }
                    }
                    else
                    {
                        var request = context.Request;
                        request.EnableBuffering();
                        if (request.Method.ToLower().Equals("post"))
                        {
                            request.Body.Seek(0, SeekOrigin.Begin);
                            using var reader = new StreamReader(request.Body, Encoding.UTF8);
                            paras = reader.ReadToEnd();
                        }
                    }
                    #endregion

                    string mesage = $"时间:{DateTime.Now.ToString()}\r\n" +
                        $"URL：{context.Request.Path}\r\n\r\n" +
                        $"Params：{paras}\r\n\r\n" +
                        $"消息：" + ex.Message + "\r\n\r\n\r\n";
                    string basePath = _configuration["Logs:Path"];
                    string fileName = DateTime.Now.ToString("yyyyMMdd") + ".txt";
                    await File.AppendAllTextAsync(basePath + fileName, mesage);
                    await context.Response.WriteAsync(result);
                }
                catch (Exception)
                {

                }
                //2.记录到数据库

                try
                {

                    string paras = "";
                    #region 请求参数
                    if (context.Request.Method.ToUpper() == "GET")
                    {
                        var keys = context.Request.Query.Keys;
                        foreach (var item in keys)
                        {
                            paras += $"{item}={context.Request.Query[item]};";
                        }
                    }
                    else
                    {
                        var request = context.Request;
                        request.EnableBuffering();
                        if (request.Method.ToLower().Equals("post"))
                        {
                            request.Body.Seek(0, SeekOrigin.Begin);
                            using var reader = new StreamReader(request.Body, Encoding.UTF8);
                            paras = reader.ReadToEnd();
                        }
                    }
                    #endregion

                    string mesage = $"时间:{DateTime.Now.ToString()}\r\n" +
                        $"URL：{context.Request.Path}\r\n\r\n" +
                        $"Params：{paras}\r\n\r\n" +
                        $"消息：" + ex.Message + "\r\n\r\n\r\n";

                    log_Service.Add_Error(new Learn.Infraestrutura.EFCore.SysErrorLogs
                    {
                        ElcreateTime = DateTime.Now,
                        Elapi= context.Request.Path,
                        Eldesc="",
                        Elid=Config.GUID(),
                        Elip=Config.GetIp(),
                        Elmessage=ex.Message,
                        Elparams=paras,
                        Eluid=null
                    });
                }
                catch (Exception)
                {

                }
            }
        }

    }
}
